package com.leyou.auth.controller;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.pojo.Payload;
import com.leyou.auth.pojo.UserInfo;
import com.leyou.auth.service.AuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LeYouException;
import com.leyou.user.pojo.User;
import com.leyou.utils.CookieUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.handler.UserRoleAuthorizationInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author: Rose
 * @Date: 2021/4/10 16:33
 * @description ${description}
 * @version: 1.0.0
 */
@Slf4j
@EnableConfigurationProperties(JwtProperties.class)
@RestController
@RequestMapping("/")
public class AuthController {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private AuthService authService;

    public static final String JWT_TOKEN_NAME = "LY_TOKEN";


    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestParam("username") String username,
                                        @RequestParam("password") String password,
                                        HttpServletResponse response,
                                        HttpServletRequest request) {
        // 登录
        String token = this.authService.login(username, password);
        // TODO 写入cookie
        /*Cookie cookie = new Cookie(jwtProperties.getCookieName(), token);
        cookie.setMaxAge(10000000);
        cookie.setPath("");
        cookie.setDomain("");
        cookie.setHttpOnly(false);
        response.addCookie(cookie);*/
        //CookieUtils.setCookie(request,response,jwtProperties.getCookieName(),token,3600,false);
        log.info("保存的Cookie的key:{},值:{}", jwtProperties.getCookieName(), token);
        CookieUtils.builder(response).httpOnly(false).request(request).build(jwtProperties.getCookieName(), token);

        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }


    /**
     * 校验用户登录状态
     *
     * @return
     */
    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(@CookieValue(value = AuthController.JWT_TOKEN_NAME) String token, HttpServletResponse response,
                                           HttpServletRequest request) {
        if (StringUtils.isBlank(token)) {
            // 如果没有 token, 证明未登录,返回403
            throw new LeYouException(ExceptionEnum.UNAUTHORIZED);
        }
        try {
            // 解析token
            Payload<UserInfo> infoFromToken = JwtUtils.getInfoFromToken(token, jwtProperties.getPubKey(), UserInfo.class);
            UserInfo info = infoFromToken.getUserInfo();

            //如果获取用户信息成功,则需要刷新token, 重新生成token
            String newtoken = JwtUtils.generateTokenExpireInMinutes(info, jwtProperties.getPriKey(), jwtProperties.getExpire());

            log.info("刷新token,重新保存的Cookie的key:{},值:{}", jwtProperties.getCookieName(), newtoken);
            // 然后写入cookie汇总,
            // 将token 写入cookie,并指定httpOnly为true, 防止通过js获取和修改
            CookieUtils.builder(response).httpOnly(true).request(request).build(jwtProperties.getCookieName(), newtoken);
            // 已登录返回用户信息
            return ResponseEntity.ok(info);
        } catch (Exception e) {

            // token 已经过期,或者token 被篡改
            throw new LeYouException(ExceptionEnum.UNAUTHORIZED);
        }
    }


}
